from fastapi import FastAPI
from redis import asyncio as aioredis

def register_redis(app: FastAPI, config: dict):
    """
    Register redis client to app.state.redis
    app: fastapi app实例
    config: redis 配置信息
    """

    async def reddis_pool():
        redis = await aioredis.from_url(f"redis://{config.get('username')}:{config.get('password')}@{config.get('host')}:{config.get('port')}/{config.get('db')}", decode_responses=True)
        return redis

    @app.on_event("startup")
    async def startup():
        app.state.redis = await reddis_pool()
        print("初始化redis连接池", id(app.state.redis))